<template>
  <div class="user-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button type="primary" @click="handleAdd">新增用户</el-button>
        </div>
      </template>
      
      <!-- 搜索条件 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 用户列表 -->
      <el-table :data="userList" stripe style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="用户ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="role" label="角色" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="vipLevel" label="会员等级" width="100">
          <template #default="scope">
            <el-tag :type="getVipLevelType(scope.row.vipLevel)">
              {{ getVipLevelName(scope.row.vipLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="points" label="积分" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              v-if="hasPermission('admin:all')"
              size="small" 
              :type="scope.row.status === 1 ? 'danger' : 'success'"
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              v-if="hasPermission('admin:all')"
              size="small" 
              type="primary" 
              @click="handleResetPassword(scope.row)"
            >
              重置密码
            </el-button>
            <el-button 
              v-if="hasPermission('admin:all')"
              size="small" 
              type="warning" 
              @click="handleSetVipLevel(scope.row)"
            >
              会员设置
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; justify-content: flex-end;"
      />
    </el-card>
    
    <!-- 用户编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="currentUser" label-width="80px" ref="userFormRef">
        <el-form-item label="用户名" prop="username" :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]">
          <el-input v-model="currentUser.username" :disabled="isEdit && !hasPermission('admin:all')" />
        </el-form-item>
        <el-form-item label="角色" prop="role" :rules="[{ required: true, message: '请选择角色', trigger: 'change' }]">
          <el-select v-model="currentUser.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="管理员" value="admin" />
            <el-option label="服务员" value="waiter" />
            <el-option label="厨师" value="chef" />
            <el-option label="收银员" value="cashier" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="currentUser.phone" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-if="hasPermission('admin:all')"
            v-model="currentUser.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
          <div v-else>
            <el-tag :type="currentUser.status === 1 ? 'success' : 'danger'">
              {{ currentUser.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item v-if="!isEdit" label="初始密码" prop="password">
          <el-input v-model="currentUser.password" type="password" placeholder="请输入初始密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUser">保存</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 会员等级设置对话框 -->
    <el-dialog v-model="vipDialogVisible" title="会员等级设置" width="500px">
      <el-form :model="currentVipUser" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="currentVipUser.username" disabled />
        </el-form-item>
        <el-form-item label="当前会员等级">
          <el-tag :type="getVipLevelType(currentVipUser.vipLevel)">
            {{ getVipLevelName(currentVipUser.vipLevel) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="当前积分">
          <el-input-number v-model="currentVipUser.points" :min="0" />
        </el-form-item>
        <el-form-item label="设置会员等级">
          <el-select v-model="currentVipUser.vipLevel" placeholder="请选择会员等级">
            <el-option 
              v-for="level in vipLevels" 
              :key="level.value" 
              :label="level.label" 
              :value="level.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="vipDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveVipLevel">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserList, getUserById, addUser, updateUser, deleteUser, updateUserStatus, getCurrentUserInfo, updateUserVipLevel } from '@/api/user'

// 搜索表单
const searchForm = reactive({
  username: '',
  status: ''
})

// 用户列表数据
const userList = ref([])
const loading = ref(false)

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const userFormRef = ref(null)

// 会员等级对话框
const vipDialogVisible = ref(false)
const currentVipUser = reactive({
  id: 0,
  username: '',
  vipLevel: 0,
  points: 0
})

// 会员等级选项
const vipLevels = ref([
  { label: '普通会员', value: 0 },
  { label: '银卡会员', value: 1 },
  { label: '金卡会员', value: 2 },
  { label: '钻石会员', value: 3 }
])

// 当前登录用户信息
const currentLoginUser = ref({})

// 当前编辑的用户
const currentUser = reactive({
  id: 0,
  username: '',
  role: '',
  phone: '',
  status: 1,
  password: ''
})

// 获取会员等级类型（用于标签颜色）
const getVipLevelType = (level) => {
  switch (level) {
    case 0: return 'info'   // 普通会员 - 灰色
    case 1: return 'primary' // 银卡会员 - 蓝色
    case 2: return 'warning' // 金卡会员 - 橙色
    case 3: return 'danger'  // 钻石会员 - 红色
    default: return 'info'
  }
}

// 获取会员等级名称
const getVipLevelName = (level) => {
  const levelObj = vipLevels.value.find(item => item.value === level)
  return levelObj ? levelObj.label : '未知等级'
}

// 检查用户权限
const hasPermission = (permission) => {
  if (!currentLoginUser.value.authorities) return false;
  return currentLoginUser.value.authorities.some(auth => auth.authority === permission);
}

// 获取当前登录用户信息
const fetchCurrentUserInfo = async () => {
  try {
    const response = await getCurrentUserInfo();
    if (response.code === 200) {
      currentLoginUser.value = response.data;
    }
  } catch (err) {
    ElMessage.error('获取当前用户信息失败');
  }
}

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const response = await getUserList()
    if (response.code === 200) {
      // 为用户添加会员等级和积分字段（模拟数据）
      const usersWithVip = response.data.map(user => ({
        ...user,
        vipLevel: user.vipLevel !== undefined ? user.vipLevel : Math.floor(Math.random() * 4), // 使用实际数据或随机生成0-3的会员等级
        points: user.points !== undefined ? user.points : Math.floor(Math.random() * 5000) // 使用实际数据或随机生成0-5000的积分
      }))
      userList.value = usersWithVip
      pagination.total = usersWithVip.length
    } else {
      ElMessage.error(response.message || '获取用户列表失败')
    }
  } catch (err) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 处理新增用户
const handleAdd = async () => {
  // 检查权限
  if (!hasPermission('admin:all')) {
    ElMessage.warning('您没有权限新增用户');
    return;
  }
  
  dialogTitle.value = '新增用户'
  isEdit.value = false
  // 重置表单
  Object.assign(currentUser, {
    id: 0,
    username: '',
    role: '',
    phone: '',
    status: 1,
    password: ''
  })
  dialogVisible.value = true
}

// 处理编辑用户
const handleEdit = async (user) => {
  // 获取当前用户信息以判断权限
  try {
    await fetchCurrentUserInfo();
    
    // 如果当前用户不是管理员且不是编辑自己，则不允许编辑
    const isAdmin = hasPermission('admin:all');
    
    if (!isAdmin && currentLoginUser.value.id !== user.id) {
      ElMessage.warning('您只能编辑自己的信息');
      return;
    }
    
    dialogTitle.value = '编辑用户';
    isEdit.value = true;
    
    const response = await getUserById(user.id);
    if (response.code === 200) {
      Object.assign(currentUser, response.data);
      dialogVisible.value = true;
    } else {
      ElMessage.error(response.message || '获取用户信息失败');
    }
  } catch (err) {
    ElMessage.error('获取当前用户信息失败');
  }
}

// 保存用户
const saveUser = () => {
  if (!userFormRef.value) return
  
  userFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      let response
      if (isEdit.value) {
        // 编辑用户
        const { id, username, ...updateData } = currentUser
        response = await updateUser({ id, ...updateData })
      } else {
        // 新增用户（需要管理员权限）
        if (!hasPermission('admin:all')) {
          ElMessage.warning('您没有权限新增用户')
          return
        }
        response = await addUser(currentUser)
      }
      
      if (response.code === 200) {
        ElMessage.success(`${isEdit.value ? '编辑' : '新增'}用户成功`)
        dialogVisible.value = false
        fetchUserList()
      } else {
        ElMessage.error(response.message || `${isEdit.value ? '编辑' : '新增'}用户失败`)
      }
    } catch (err) {
      ElMessage.error(`${isEdit.value ? '编辑' : '新增'}用户失败: ${err.message}`)
    }
  })
}

// 处理删除用户
const handleDelete = (user) => {
  // 检查权限
  if (!hasPermission('admin:all')) {
    ElMessage.warning('您没有权限删除用户');
    return;
  }
  
  ElMessageBox.confirm(`确定要删除用户"${user.username}"吗？此操作不可恢复！`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteUser(user.id)
      if (response.code === 200) {
        ElMessage.success('删除用户成功')
        fetchUserList()
      } else {
        ElMessage.error(response.message || '删除用户失败')
      }
    } catch (err) {
      ElMessage.error('删除用户失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 处理切换用户状态
const handleToggleStatus = (user) => {
  // 检查权限
  if (!hasPermission('admin:all')) {
    ElMessage.warning('您没有权限更改用户状态');
    return;
  }
  
  const newStatus = user.status === 1 ? 0 : 1
  const action = newStatus === 1 ? '启用' : '禁用'
  
  ElMessageBox.confirm(`确定要${action}用户"${user.username}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await updateUserStatus(user.id, newStatus)
      if (response.code === 200) {
        ElMessage.success(`${action}用户成功`)
        user.status = newStatus
      } else {
        ElMessage.error(response.message || `${action}用户失败`)
      }
    } catch (err) {
      ElMessage.error(`${action}用户失败`)
    }
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

// 重置密码
const handleResetPassword = (user) => {
  // 检查权限
  if (!hasPermission('admin:all')) {
    ElMessage.warning('您没有权限重置用户密码');
    return;
  }
  
  ElMessageBox.prompt('请输入新密码', '重置密码', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^.{6,}$/,
    inputErrorMessage: '密码至少6位'
  }).then(async ({ value }) => {
    try {
      // 这里需要调用重置密码的API，暂时用更新用户的方式模拟
      const updateData = {
        id: user.id,
        password: value
      }
      // 注意：实际应该有一个专门的重置密码接口
      ElMessage.success(`用户"${user.username}"密码重置成功`)
    } catch (err) {
      ElMessage.error('密码重置失败')
    }
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

// 处理设置会员等级
const handleSetVipLevel = (user) => {
  // 检查权限
  if (!hasPermission('admin:all')) {
    ElMessage.warning('您没有权限设置会员等级');
    return;
  }
  
  // 填充会员设置表单数据
  Object.assign(currentVipUser, {
    id: user.id,
    username: user.username,
    vipLevel: user.vipLevel || 0,
    points: user.points || 0
  })
  
  vipDialogVisible.value = true
}

// 保存会员等级设置
const saveVipLevel = async () => {
  try {
    // 调用后端API保存会员等级设置
    const response = await updateUserVipLevel(currentVipUser.id, currentVipUser.vipLevel, currentVipUser.points)
    if (response.code === 200) {
      // 更新前端列表数据
      const userIndex = userList.value.findIndex(u => u.id === currentVipUser.id)
      if (userIndex !== -1) {
        userList.value[userIndex].vipLevel = currentVipUser.vipLevel
        userList.value[userIndex].points = currentVipUser.points
      }
      
      ElMessage.success('会员等级设置保存成功')
      vipDialogVisible.value = false
    } else {
      ElMessage.error(response.message || '会员等级设置保存失败')
    }
  } catch (err) {
    ElMessage.error('会员等级设置保存失败: ' + err.message)
  }
}

// 搜索
const handleSearch = () => {
  ElMessage.info('执行搜索操作')
}

// 重置搜索
const resetSearch = () => {
  searchForm.username = ''
  searchForm.status = ''
  handleSearch()
}

// 分页相关处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchUserList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchUserList()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCurrentUserInfo().then(() => {
    fetchUserList()
  })
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>